<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="商家名称" prop="shopName">
        <el-input v-model="formData.shopName" placeholder="商家名称" />
      </el-form-item>
      <el-form-item label="分类" prop="category">
        <div class="category-container">
          <div class="default-categories">
            <el-tag
              v-for="(tag, index) in defaultCategories"
              :key="index"
              class="category-tag"
              :class="{ 'selected-tag': isTagSelected(tag) }"
              @click="toggleCategory(tag)"
            >
              {{ tag }}
            </el-tag>
          </div>
          <el-input
            v-model="formData.category"
            type="textarea"
            :rows="2"
            placeholder="请输入分类，多个分类用逗号分隔（最多2个）"
            @input="validateCategories"
          />
          <div class="selected-tags" v-if="categoryTags.length > 0">
            <span class="tag-label">已选分类：</span>
            <el-tag
              v-for="(tag, index) in categoryTags"
              :key="index"
              closable
              @close="removeCategory(index)"
            >
              {{ tag }}
            </el-tag>
          </div>
        </div>
      </el-form-item>
      <!-- 其他表单字段保持不变 -->
      <el-form-item label="消息标题" prop="title">
        <el-input v-model="formData.title" placeholder="请输入消息标题" />
      </el-form-item>
      <el-form-item label="消息内容" prop="content">
        <el-input v-model="formData.content" type="textarea" placeholder="请输入消息内容" />
      </el-form-item>
      <el-form-item label="图片" prop="images">
        <UploadImg v-model="formData.images" />
      </el-form-item>
      <el-form-item label="发布日期" prop="publishDate">
        <el-date-picker
          v-model="formData.publishDate"
          type="date"
          value-format="x"
          placeholder="选择发布日期"
        />
      </el-form-item>

    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
    import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
    import { MessageApi, MessageVO } from '@/api/shequ/message'
    import { computed, ref, reactive } from 'vue'

    /** 商家消息 表单 */
    defineOptions({ name: 'MessageForm' })

    const { t } = useI18n() // 国际化
    const message = useMessage() // 消息弹窗

    const dialogVisible = ref(false) // 弹窗的是否展示
    const dialogTitle = ref('') // 弹窗的标题
    const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
    const formType = ref('') // 表单的类型：create - 新增；update - 修改
    const formData = ref({
        id: undefined,
        category: undefined,
        title: undefined,
        content: undefined,
        images: undefined,
        status: 1,
        publishDate: undefined,
        shopName: undefined
    })

    // 默认分类选项
    const defaultCategories = ref([
        '新品上市',
        '🔥 热销爆款',
        '🛍️ 每日特惠',
        '🍱 食品生鲜',
        '🎁 买赠福利',
        '🧼 家居清洁',
        '🥭 当季热卖',
        '💰 特价专区',
        '🍅 新鲜蔬菜',
        '☀️ 夏日冰爽'
    ])

    // 计算当前已选的分类标签
    const categoryTags = computed(() => {
        if (!formData.value.category) return []
        return formData.value.category.split(',').filter(tag => tag.trim() !== '')
    })

    // 检查标签是否已被选中
    const isTagSelected = (tag: string) => {
        return categoryTags.value.includes(tag)
    }

    // 切换分类标签的选择状态
    const toggleCategory = (tag: string) => {
        const tags = [...categoryTags.value]
        const index = tags.indexOf(tag)

        if (index > -1) {
            // 如果已存在，则移除
            tags.splice(index, 1)
        } else {
            // 如果未存在且未超过限制，则添加
            if (tags.length >= 2) {
                message.warning('最多只能选择2个分类标签')
                return
            }
            tags.push(tag)
        }

        formData.value.category = tags.join(',')
    }

    // 移除分类标签
    const removeCategory = (index: number) => {
        const tags = [...categoryTags.value]
        tags.splice(index, 1)
        formData.value.category = tags.join(',')
    }

    // 验证分类输入
    const validateCategories = () => {
        if (!formData.value.category) return

        const tags = formData.value.category.split(',')
            .map(tag => tag.trim())
            .filter(tag => tag !== '')

        if (tags.length > 2) {
            message.warning('最多只能选择2个分类标签')
            formData.value.category = tags.slice(0, 2).join(',')
        }
    }

    const formRules = reactive({
        category: [
            { required: true, message: '请至少选择一个分类标签', trigger: 'blur' },
            {
                validator: (rule: any, value: any, callback: any) => {
                    if (!value || value.split(',').filter((t: string) => t.trim() !== '').length === 0) {
                        callback(new Error('请至少选择一个分类标签'))
                    } else {
                        callback()
                    }
                },
                trigger: 'blur'
            }
        ],
        title: [{ required: true, message: '消息标题不能为空', trigger: 'blur' }],
        content: [{ required: true, message: '消息内容不能为空', trigger: 'blur' }],
        publishDate: [{ required: true, message: '发布日期不能为空', trigger: 'blur' }],
        shopName: [{ required: true, message: '商家信息不能为空', trigger: 'blur' }]
    })

    const formRef = ref() // 表单 Ref

    /** 打开弹窗 */
    const open = async (type: string, id?: number) => {
        dialogVisible.value = true
        dialogTitle.value = t('action.' + type)
        formType.value = type
        resetForm()
        // 修改时，设置数据
        if (id) {
            formLoading.value = true
            try {
                formData.value = await MessageApi.getMessage(id)
            } finally {
                formLoading.value = false
            }
        }
    }
    defineExpose({ open }) // 提供 open 方法，用于打开弹窗

    /** 提交表单 */
    const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
    const submitForm = async () => {
        // 校验表单
        await formRef.value.validate()
        // 提交请求
        formLoading.value = true
        try {
            const data = formData.value as unknown as MessageVO
            if (formType.value === 'create') {
                await MessageApi.createMessage(data)
                message.success(t('common.createSuccess'))
            } else {
                await MessageApi.updateMessage(data)
                message.success(t('common.updateSuccess'))
            }
            dialogVisible.value = false
            // 发送操作成功的事件
            emit('success')
        } finally {
            formLoading.value = false
        }
    }

    /** 重置表单 */
    const resetForm = () => {
        formData.value = {
            id: undefined,
            category: undefined,
            title: undefined,
            content: undefined,
            images: undefined,
            status: 1,
            publishDate: undefined,
            shopName: undefined
        }
        formRef.value?.resetFields()
    }
</script>

<style scoped>
  .category-container {
    width: 100%;
  }

  .default-categories {
    margin-bottom: 10px;
  }

  .category-tag {
    margin-right: 8px;
    margin-bottom: 8px;
    cursor: pointer;
  }

  .category-tag.selected-tag {
    background-color: var(--el-color-primary);
    color: white;
  }

  .selected-tags {
    margin-top: 8px;
    display: flex;
    align-items: center;
    flex-wrap: wrap;
  }

  .tag-label {
    margin-right: 8px;
    color: var(--el-text-color-secondary);
    font-size: 14px;
  }

  .selected-tags .el-tag {
    margin-right: 8px;
    margin-bottom: 8px;
  }
</style>
